from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship
from models.user import Base
from datetime import datetime

# 多对多关系表：帖子与标签
post_tag_association = Table(
    'post_tags',
    Base.metadata,
    Column('post_id', Integer, ForeignKey('posts.id'), primary_key=True),
    Column('tag_id', Integer, ForeignKey('tags.id'), primary_key=True)
)


class Post(Base):
    """帖子模型"""
    __tablename__ = "posts"
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(200), nullable=False)  # 标题
    content = Column(Text, nullable=True)  # 内容描述
    images = Column(Text, nullable=True)  # 图片URL列表（JSON字符串）
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)  # 作者ID
    category = Column(String(50), nullable=True, index=True)  # 分类（推荐、摄影、搞笑等）
    
    # 统计数据
    likes = Column(Integer, default=0)  # 点赞数
    views = Column(Integer, default=0)  # 浏览数
    comments = Column(Integer, default=0)  # 评论数
    collects = Column(Integer, default=0)  # 收藏数
    
    # 时间戳
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    
    # 关系
    author = relationship("User", backref="posts")
    tags = relationship("Tag", secondary=post_tag_association, back_populates="posts")


class Tag(Base):
    """标签模型"""
    __tablename__ = "tags"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(50), unique=True, nullable=False, index=True)  # 标签名称
    tag_type = Column(String(20), default='content')  # 标签类型：category（分类标签）或 content（内容标签）
    created_at = Column(DateTime, default=datetime.now)
    
    # 关系
    posts = relationship("Post", secondary=post_tag_association, back_populates="tags")

